<?php
declare(strict_types=1);
namespace app\admin\controller;
use aphp\core\Jump;

/**
 * 后台首页
 */
class Index
{
    use Jump;
    protected string $middleware = 'rbac';

    // 首页
    public function index()
    {
        config('debug_bar.is_hide', true);
        return view();
    }

    // home
    public function home()
    {
        $sys = [
            '系统版本' => '一鱼CMS(AphpCMS) v1.1.1',
            'UI框架' => 'Pear Admin Layui v3.x(Layui v2.9.23)',
            '域名IP' => $_SERVER['SERVER_NAME'] . ' [ ' . gethostbyname($_SERVER['SERVER_NAME']) . ' ]',
            '操作系统' => PHP_OS,
            '运行环境' => $_SERVER["SERVER_SOFTWARE"],
            'PHP版本' => 'PHP ' . PHP_VERSION,
            'PHP运行方式' => php_sapi_name(),
            '上传附件限制' => ini_get('upload_max_filesize'),
            '执行时间限制' => ini_get('max_execution_time') . '秒',
            '服务器时间' => date("Y年n月j日 H:i:s"),
        ];
        return view()->with('sys', $sys);
    }

    // 菜单api
    public function api_menu()
    {
        $group_id = session('user.group_id'); // 用户组ID
        if ($group_id == 1) {
            return widget('menu_tree')->get(); // 超级管理
        }
        $auth = widget('auth')->get($group_id); // 获取用户组权限
        $where = empty($auth['auth_menu']) ? ['id' => 2] : ['id' => ['in', $auth['auth_menu']]]; // 不存在则只显示首页
        return widget('menu_tree')->get('', ['where' => $where]);
    }

    // 工作菜单
    public function work_menu(array $req)
    {
        $user = session('user');
        $menu_list = widget('menu_work')->get();
        if ($user['group_id'] != 1) {
            $auth = widget('auth')->get($user['group_id']); // 获取用户组权限
            $auth_menu = explode(',', $auth['auth_menu']);
            $menu_list = array_filter($menu_list, fn($k) => in_array($k, $auth_menu), ARRAY_FILTER_USE_KEY);
        }
        if ($this->isPost()) {
            $menu_ids = ids_filter($req['work_menu'], true);
            if (count($menu_ids) > 8) {
                $this->error('快捷菜单数量不能超过8个');
            }
            $menu_ids = empty($menu_ids) ? ' ' : implode(',', $menu_ids);
            $r = db('admin')->where('id', $user['id'])->setField('work_menu', $menu_ids);
            session('user.work_menu', $menu_ids);
            $this->_jump(['设置快捷菜单成功', '设置快捷菜单失败'], $r, 'home');
        }
        return view()->with(['menu_list' => $menu_list, 'work_menu' => $user['work_menu']]);
    }
}